package com.atguigu.flink.chapter07_state;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/10/28
 *
 * 检测传感器的水位值，如果连续的两个水位值超过10，就输出报警。
 *
 *      每种传感器，需要和这种传感器上一个传感器的vc进行对比。
 *          需要 保存上一个传感器的vc(单值)
 *
 *          单值: ValueState
 */
public class Demo5_ValueState
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .keyBy(WaterSensor::getId)
           .process(new KeyedProcessFunction<String, WaterSensor, String>()
           {

               //保存上个传感器vc值的变量
               private ValueState<Integer> lastVc;

               //task启动时，只执行一次。 获取状态
               @Override
               public void open(Configuration parameters) throws Exception {
                   lastVc = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVc", Integer.class));
               }

               /*
                                   WaterSensor value: 当前数据
                               */
               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                   //如果第一条数据来， ValueState<Integer> lastVc什么都没有
                   if (lastVc.value() != null && lastVc.value() > 10 && value.getVc() > 10){
                       out.collect(ctx.getCurrentKey()+"连续两个传感器水位超过10，报警!");
                   }

                   //当前数据的vc保存起来，方便下次使用
                   lastVc.update(value.getVc());

                   out.collect(value.toString());

               }
           }).print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
